package com.infobip.ftpclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

/**
 * Class that is used for threads if there is need to start parallel upload
 * tests
 * 
 * @author
 * 
 */
public class FTPClientThread extends Thread {

	/*** The default FTP control port (21). ***/
	public static final int FTP_PORT = 21;

	private final String host;
	private final String user;
	private final String pass;
	private final File file;

	FTPStatistic statistic;

	public FTPClientThread(String host, String user, String pass, File file,
			FTPStatistic ftpStatistic) {
		this.host = host;
		this.pass = pass;
		this.user = user;
		this.file = file;
		this.statistic = ftpStatistic;
	}

	public FTPStatistic getStatistic() {
		return statistic;
	}

	@Override
	public void run() {

		FTP ftp = new FTP();

		String errorMessage = null;

		statistic.setFileName(file.getName());

		boolean error = false;

		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
		} catch (FileNotFoundException e1) {
			error = true;
			errorMessage = "Cannot find file: " + file.getName();
			statistic.setError(error);
			statistic.setMessage(errorMessage);

		}

		try {
			// Connecting to FTP Server
			ftp.connect(host, FTP_PORT, user, pass);

		} catch (IOException e) {
			error = true;
			errorMessage = "Error during connecting to host: " + host;
			statistic.setError(error);
			statistic.setMessage(errorMessage + " " + e.getMessage());

		}

		boolean isStored = false;

		try {
			if (!error) {
				// Get started upload time
				double startTime = new Date().getTime();
				isStored = ftp.stor(fileInputStream, file.getName());
				// Get finished upload time
				double finishTime = new Date().getTime();
				// Check if file is stored
				if (isStored) {
					// Get length of file in bytes
					double fileSizeInBytes = file.length();
					// Set statistics
					statistic.setStartTime(startTime);
					statistic.setFinishTime(finishTime);
					statistic.setFileSize(fileSizeInBytes);

				} else {
					error = true;
					errorMessage = "Error while uploading file: "
							+ file.getName();
					statistic.setError(error);
					statistic.setMessage(errorMessage);
				}
			}
		} catch (IOException e) {
			error = true;
			errorMessage = "Error while uploading file: " + file.getName();
			statistic.setError(error);
			statistic.setMessage(errorMessage + " " + e.getMessage());
		}

		try {
			if (!error) {
				ftp.disconnect();
			}
		} catch (IOException e) {
			error = true;
			errorMessage = "Error while closing FTP connection.";
			statistic.setError(error);
			statistic.setMessage(errorMessage + " " + e.getMessage());
		}

	}

}
